package org.example.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.example.kafka.KafkaProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * @date 2022/12/6 16:28
 * @decrption 程序启动后直接开始推送
 */
@Component
@Order(value = 1)
@Slf4j
@Data
public class ApplicationStartRunner implements ApplicationRunner {

    @Value(value = "${json.area}")
    private  String area;
    private JSONObject jsonObject = new JSONObject();
    @Autowired
    private KafkaProducer kafkaProducer;

    public void init() {
        File file = new File(area);
        InputStream config = null;
        try {
            config = new FileInputStream(file);
            jsonObject = JSON.parseObject(config, JSONObject.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 读取需要推送的json文件
        init();
        // 循环推送
        while(true){
//        for(int i = 0; i < 10 ; i++){
            System.out.println("task is running.");
            kafkaProducer.send(JSON.toJSONString(jsonObject));
            Thread.sleep(1000);
        }

    }
}
